from django.contrib import admin
from django.utils.html import format_html
from django.urls import reverse
from django.utils.safestring import mark_safe
from django.db.models import Count, Avg
from django.contrib.admin import SimpleListFilter
from django.utils import timezone
from datetime import datetime, timedelta
from .models import Movie, CinemaHall, Screening, Seat, Order, UserProfile, MovieReview

# 自定义过滤器
class MovieStatusFilter(SimpleListFilter):
    title = '上映状态'
    parameter_name = 'movie_status'

    def lookups(self, request, model_admin):
        return (
            ('active', '正在上映'),
            ('inactive', '已下映'),
            ('upcoming', '即将上映'),
        )

    def queryset(self, request, queryset):
        today = timezone.now().date()
        if self.value() == 'active':
            return queryset.filter(is_active=True, release_date__lte=today)
        elif self.value() == 'inactive':
            return queryset.filter(is_active=False)
        elif self.value() == 'upcoming':
            return queryset.filter(release_date__gt=today)

class OrderStatusFilter(SimpleListFilter):
    title = '订单状态'
    parameter_name = 'order_status'

    def lookups(self, request, model_admin):
        return Order.ORDER_STATUS

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(status=self.value())

# 自定义内联类
class ScreeningInline(admin.TabularInline):
    model = Screening
    extra = 1
    fields = ('hall', 'start_time', 'end_time', 'price', 'is_active')
    readonly_fields = ('end_time',)

class SeatInline(admin.TabularInline):
    model = Seat
    extra = 5
    fields = ('row', 'column', 'seat_number', 'is_active')

class MovieReviewInline(admin.TabularInline):
    model = MovieReview
    extra = 0
    readonly_fields = ('user', 'movie', 'rating', 'comment', 'created_at')
    can_delete = False

# 电影管理
@admin.register(Movie)
class MovieAdmin(admin.ModelAdmin):
    list_display = ('title', 'director', 'genre', 'duration', 'rating', 'price', 'release_date', 'is_active', 'poster_preview', 'screening_count')
    list_filter = (MovieStatusFilter, 'genre', 'release_date', 'is_active')
    search_fields = ('title', 'director', 'actors', 'description')
    list_editable = ('price', 'is_active', 'rating')
    readonly_fields = ('created_at', 'updated_at', 'poster_preview')
    prepopulated_fields = {'title': ('title',)}
    date_hierarchy = 'release_date'
    ordering = ('-release_date', 'title')
    
    fieldsets = (
        ('基本信息', {
            'fields': ('title', 'director', 'actors', 'genre', 'duration', 'description')
        }),
        ('海报和评分', {
            'fields': ('poster', 'poster_preview', 'rating')
        }),
        ('价格和上映', {
            'fields': ('price', 'release_date', 'is_active')
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    
    inlines = [ScreeningInline, MovieReviewInline]
    
    def poster_preview(self, obj):
        if obj.poster:
            return format_html(
                '<img src="{}" style="max-height: 50px; max-width: 50px; border-radius: 5px;" />',
                obj.poster.url
            )
        return "无海报"
    poster_preview.short_description = '海报预览'
    
    def screening_count(self, obj):
        return obj.screening_set.count()
    screening_count.short_description = '场次数量'
    
    actions = ['activate_movies', 'deactivate_movies', 'update_ratings']
    
    def activate_movies(self, request, queryset):
        updated = queryset.update(is_active=True)
        self.message_user(request, f'成功激活 {updated} 部电影')
    activate_movies.short_description = "激活选中的电影"
    
    def deactivate_movies(self, request, queryset):
        updated = queryset.update(is_active=False)
        self.message_user(request, f'成功下映 {updated} 部电影')
    deactivate_movies.short_description = "下映选中的电影"
    
    def update_ratings(self, request, queryset):
        for movie in queryset:
            avg_rating = movie.moviereview_set.aggregate(Avg('rating'))['rating__avg']
            if avg_rating:
                movie.rating = round(avg_rating, 1)
                movie.save()
        self.message_user(request, f'成功更新 {queryset.count()} 部电影的评分')
    update_ratings.short_description = "更新电影评分"

# 影厅管理
@admin.register(CinemaHall)
class CinemaHallAdmin(admin.ModelAdmin):
    list_display = ('name', 'hall_type', 'capacity', 'is_active', 'seat_count', 'screening_count')
    list_filter = ('hall_type', 'is_active')
    search_fields = ('name',)
    list_editable = ('is_active',)
    ordering = ('name',)
    
    inlines = [SeatInline]
    
    def seat_count(self, obj):
        return obj.seat_set.count()
    seat_count.short_description = '座位数'
    
    def screening_count(self, obj):
        return obj.screening_set.count()
    screening_count.short_description = '场次数'
    
    actions = ['activate_halls', 'deactivate_halls']
    
    def activate_halls(self, request, queryset):
        updated = queryset.update(is_active=True)
        self.message_user(request, f'成功激活 {updated} 个影厅')
    activate_halls.short_description = "激活选中的影厅"
    
    def deactivate_halls(self, request, queryset):
        updated = queryset.update(is_active=False)
        self.message_user(request, f'成功停用 {updated} 个影厅')
    deactivate_halls.short_description = "停用选中的影厅"

# 场次管理
@admin.register(Screening)
class ScreeningAdmin(admin.ModelAdmin):
    list_display = ('movie', 'hall', 'start_time', 'end_time', 'price', 'is_active', 'order_count')
    list_filter = ('is_active', 'hall__hall_type', 'start_time')
    search_fields = ('movie__title', 'hall__name')
    list_editable = ('price', 'is_active')
    date_hierarchy = 'start_time'
    ordering = ('-start_time',)
    
    fieldsets = (
        ('场次信息', {
            'fields': ('movie', 'hall', 'start_time', 'end_time', 'price', 'is_active')
        }),
        ('时间信息', {
            'fields': ('created_at',),
            'classes': ('collapse',)
        }),
    )
    
    readonly_fields = ('end_time', 'created_at')
    
    def order_count(self, obj):
        return obj.order_set.count()
    order_count.short_description = '订单数'
    
    actions = ['activate_screenings', 'deactivate_screenings']
    
    def activate_screenings(self, request, queryset):
        updated = queryset.update(is_active=True)
        self.message_user(request, f'成功激活 {updated} 个场次')
    activate_screenings.short_description = "激活选中的场次"
    
    def deactivate_screenings(self, request, queryset):
        updated = queryset.update(is_active=False)
        self.message_user(request, f'成功停用 {updated} 个场次')
    deactivate_screenings.short_description = "停用选中的场次"

# 座位管理
@admin.register(Seat)
class SeatAdmin(admin.ModelAdmin):
    list_display = ('hall', 'row', 'column', 'seat_number', 'is_active')
    list_filter = ('hall', 'is_active', 'row')
    search_fields = ('seat_number', 'hall__name')
    list_editable = ('is_active',)
    ordering = ('hall', 'row', 'column')
    
    actions = ['activate_seats', 'deactivate_seats']
    
    def activate_seats(self, request, queryset):
        updated = queryset.update(is_active=True)
        self.message_user(request, f'成功激活 {updated} 个座位')
    activate_seats.short_description = "激活选中的座位"
    
    def deactivate_seats(self, request, queryset):
        updated = queryset.update(is_active=False)
        self.message_user(request, f'成功停用 {updated} 个座位')
    deactivate_seats.short_description = "停用选中的座位"

# 订单管理
@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
    list_display = ('order_id', 'user', 'movie_title', 'screening_info', 'total_amount', 'status', 'created_at', 'seat_count')
    list_filter = (OrderStatusFilter, 'created_at', 'screening__hall__hall_type')
    search_fields = ('order_id', 'user__username', 'screening__movie__title')
    readonly_fields = ('order_id', 'created_at', 'updated_at')
    date_hierarchy = 'created_at'
    ordering = ('-created_at',)
    
    fieldsets = (
        ('订单信息', {
            'fields': ('order_id', 'user', 'screening', 'seats', 'total_amount', 'status')
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    
    def movie_title(self, obj):
        return obj.screening.movie.title
    movie_title.short_description = '电影'
    
    def screening_info(self, obj):
        return f"{obj.screening.hall.name} - {obj.screening.start_time.strftime('%m-%d %H:%M')}"
    screening_info.short_description = '场次信息'
    
    def seat_count(self, obj):
        return obj.seats.count()
    seat_count.short_description = '座位数'
    
    actions = ['mark_as_paid', 'mark_as_completed', 'cancel_orders']
    
    def mark_as_paid(self, request, queryset):
        updated = queryset.update(status='paid')
        self.message_user(request, f'成功标记 {updated} 个订单为已支付')
    mark_as_paid.short_description = "标记为已支付"
    
    def mark_as_completed(self, request, queryset):
        updated = queryset.update(status='completed')
        self.message_user(request, f'成功标记 {updated} 个订单为已完成')
    mark_as_completed.short_description = "标记为已完成"
    
    def cancel_orders(self, request, queryset):
        updated = queryset.update(status='cancelled')
        self.message_user(request, f'成功取消 {updated} 个订单')
    cancel_orders.short_description = "取消订单"

# 用户资料管理
@admin.register(UserProfile)
class UserProfileAdmin(admin.ModelAdmin):
    list_display = ('user', 'phone', 'points', 'avatar_preview', 'created_at')
    list_filter = ('created_at',)
    search_fields = ('user__username', 'user__email', 'phone')
    readonly_fields = ('created_at', 'avatar_preview')
    
    def avatar_preview(self, obj):
        if obj.avatar:
            return format_html(
                '<img src="{}" style="max-height: 50px; max-width: 50px; border-radius: 50%;" />',
                obj.avatar.url
            )
        return "无头像"
    avatar_preview.short_description = '头像预览'

# 电影评论管理
@admin.register(MovieReview)
class MovieReviewAdmin(admin.ModelAdmin):
    list_display = ('user', 'movie', 'rating', 'comment_preview', 'created_at')
    list_filter = ('rating', 'created_at')
    search_fields = ('user__username', 'movie__title', 'comment')
    readonly_fields = ('created_at',)
    ordering = ('-created_at',)
    
    def comment_preview(self, obj):
        return obj.comment[:50] + '...' if len(obj.comment) > 50 else obj.comment
    comment_preview.short_description = '评论预览'

# 自定义Admin站点
admin.site.site_header = '电影院票务管理系统'
admin.site.site_title = '电影院管理后台'
admin.site.index_title = '欢迎使用电影院票务管理系统'
